﻿using HRMSystemShi.DAL;
using HRMSystemShi.Model;

namespace HRMSystemShi.BLL
{
    public class LoginUser
    {
        private string UserName;
        private string Password;

        public LoginUser(string un,string password)
        {
            UserName = un;
            Password = password;
        }

        public enum LoginType{
            Login,
            Admin,
            Deleted,
            Fail,
            Locked,
        }
        public LoginType Login()
        {
            OperatorService operatorService = new OperatorService();
            Operator? op=operatorService.GetOperator(UserName);
            OperationLog log = new OperationLog();

            log.Id = Guid.NewGuid();
            log.ActionDate = DateTime.Now;
            OperationLogService service = new OperationLogService();

            if (op == null)
            {
                log.OperatorId=Guid.Empty;
                log.ActionDesc = $"试图以不存在用户{UserName}登录";
                service.AddOperationLog(log);
                return LoginType.Fail;
            }
            else if(!OperatorService.PasswordMatch(Password))
            {
                log.OperatorId = op.Id;
                log.ActionDesc = $"用户{UserName}试图以错误密码登录";
                service.AddOperationLog(log);
                return LoginType.Fail;
            }
            else if (op.IsDeleted)
            {
                log.OperatorId = op.Id;
                log.ActionDesc = $"试图以已删除用户{UserName}登录";
                service.AddOperationLog(log);
                return LoginType.Deleted;
            }
            else if (op.IsLocked)
            {
                log.OperatorId = op.Id;
                log.ActionDesc = $"试图以已删除用户{UserName}登录";
                service.AddOperationLog(log);
                return LoginType.Locked;
            }
            else if (op.IsAdmin)
            {
                log.OperatorId = op.Id;
                log.ActionDesc = $"管理员{UserName}已登录";
                service.AddOperationLog(log);
                LoginUserInfo.GetInstance().InitMember(op.RealName, op.UserName,op.IsAdmin);
                return LoginType.Admin;
            }
            else
            {
                log.OperatorId = op.Id;
                log.ActionDesc = $"普通用户{UserName}已登录";
                service.AddOperationLog(log);
                LoginUserInfo.GetInstance().InitMember(op.RealName, op.UserName,op.IsAdmin);
                return LoginType.Login;
            }
        }
    }
}
